import { ref, reactive } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { wxLogin, logout, updateUserInfo as updateUserInfoApi } from '../api/auth';
import { getUserInfo, uploadAvatar as uploadAvatarApi } from '../api/user';
import { STORAGE_KEYS, ROUTES, DEFAULT_AVATAR } from '../constants';

// 扩展uni类型定义
declare global {
  interface Uni {
    chooseAvatar(options: {
      success: (res: { tempFilePath: string }) => void;
      fail: (err: any) => void;
    }): void;
  }
}

/**
 * 认证相关的钩子函数
 */
export default function useAuth() {
  // 登录状态
  const isLoggedIn = ref(false);
  
  // 是否需要完善用户信息
  const needUserInfo = ref(false);

  // 用户信息
  const userInfo = reactive({
    id: '',
    nickName: '',
    avatarUrl: '',
    gender: 0,
    country: '',
    province: '',
    city: ''
  });

  // 检查登录状态
  const checkLoginStatus = () => {
    const token = uni.getStorageSync(STORAGE_KEYS.TOKEN);
    
    if (token) {
      isLoggedIn.value = true;
      // 获取用户信息
      fetchUserInfo();
    } else {
      isLoggedIn.value = false;
      // 清空用户信息
      resetUserInfo();
    }
  };

  // 重置用户信息
  const resetUserInfo = () => {
    userInfo.id = '';
    userInfo.nickName = '';
    userInfo.avatarUrl = '';
    userInfo.gender = 0;
    userInfo.country = '';
    userInfo.province = '';
    userInfo.city = '';
  };

  // 获取用户信息
  const fetchUserInfo = () => {
    getUserInfo()
      .then((res: any) => {
        if (res.code === 0 && res.data) {
          Object.assign(userInfo, res.data);
          // 检查是否需要完善用户信息
          checkNeedUserInfo();
        }
      })
      .catch((err: any) => {
        console.error('获取用户信息失败', err);
      });
  };
  
  // 检查是否需要完善用户信息
  const checkNeedUserInfo = () => {
    needUserInfo.value = !userInfo.nickName || !userInfo.avatarUrl;
  };

  // 微信登录
  const handleWxLogin = () => {
    return new Promise((resolve, reject) => {
      // 显示加载提示
      uni.showLoading({
        title: '登录中...'
      });
      
      // 调用微信登录接口
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          console.log('微信登录成功', loginRes);
          // 获取登录凭证（code）
          const code = loginRes.code;
          
          // 调用后端接口，发送code获取用户信息和token
          wxLogin(code)
            .then((res: any) => {
              uni.hideLoading();
              
              // 登录成功，保存token和用户信息
              const data = res.data;
              uni.setStorageSync(STORAGE_KEYS.TOKEN, data.token);
              uni.setStorageSync(STORAGE_KEYS.USER_INFO, data.userInfo);
              
              // 更新登录状态
              isLoggedIn.value = true;
              Object.assign(userInfo, data.userInfo);
              
              // 检查是否需要完善用户信息
              needUserInfo.value = data.userInfo.needUserInfo || false;
              
              // 提示登录成功
              uni.showToast({
                title: '登录成功',
                icon: 'success'
              });
              
              resolve({
                ...data,
                needUserInfo: needUserInfo.value
              });
            })
            .catch((err: any) => {
              uni.hideLoading();
              console.error('请求登录接口失败', err);
              uni.showToast({
                title: err.message || '网络错误，请重试',
                icon: 'none'
              });
              reject(err);
            });
        },
        fail: (err) => {
          console.error('微信登录失败', err);
          uni.hideLoading();
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
          reject(err);
        }
      });
    });
  };
  
  // 选择头像
  const chooseAvatar = () => {
    return new Promise((resolve, reject) => {
      // 调用微信选择头像接口
      uni.chooseAvatar({
        success: (res) => {
          const tempFilePath = res.tempFilePath;
          // 上传头像
          uploadAvatar(tempFilePath)
            .then((avatarUrl) => {
              resolve(avatarUrl);
            })
            .catch((err) => {
              reject(err);
            });
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  };
  
  // 上传头像
  const uploadAvatar = (filePath: string) => {
    return new Promise((resolve, reject) => {
      uni.showLoading({
        title: '上传中...'
      });
      
      // 传递旧头像URL给上传API
      uploadAvatarApi(filePath, userInfo.avatarUrl)
        .then((res: any) => {
          uni.hideLoading();
          if (res.code === 0 && res.data) {
            const avatarUrl = res.data.url;
            // 更新用户信息
            updateUserInfo(userInfo.id, undefined, avatarUrl)
              .then(() => {
                userInfo.avatarUrl = avatarUrl;
                resolve(avatarUrl);
              })
              .catch((err) => {
                reject(err);
              });
          } else {
            reject(new Error('上传头像失败'));
          }
        })
        .catch((err) => {
          uni.hideLoading();
          uni.showToast({
            title: '上传头像失败',
            icon: 'none'
          });
          reject(err);
        });
    });
  };
  
  // 更新用户信息
  const updateUserInfo = (userId: string | number, nickName?: string, avatarUrl?: string) => {
    return new Promise((resolve, reject) => {
      updateUserInfoApi(userId, nickName, avatarUrl)
        .then((res: any) => {
          if (res.code === 0 && res.data) {
            // 更新本地用户信息
            Object.assign(userInfo, res.data.userInfo);
            // 保存到本地存储
            uni.setStorageSync(STORAGE_KEYS.USER_INFO, res.data.userInfo);
            // 检查是否需要完善用户信息
            checkNeedUserInfo();
            resolve(res.data.userInfo);
          } else {
            reject(new Error('更新用户信息失败'));
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  };

  // 退出登录
  const handleLogout = () => {
    return new Promise((resolve, reject) => {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用退出登录接口
            logout()
              .then(() => {
                // 清除本地存储的登录信息
                uni.removeStorageSync(STORAGE_KEYS.TOKEN);
                uni.removeStorageSync(STORAGE_KEYS.USER_INFO);
                
                // 更新登录状态
                isLoggedIn.value = false;
                needUserInfo.value = false;
                resetUserInfo();
                
                // 提示退出成功
                uni.showToast({
                  title: '已退出登录',
                  icon: 'success'
                });
                
                resolve(true);
              })
              .catch((err: any) => {
                console.error('退出登录失败', err);
                // 即使接口调用失败，也清除本地存储的登录信息
                uni.removeStorageSync(STORAGE_KEYS.TOKEN);
                uni.removeStorageSync(STORAGE_KEYS.USER_INFO);
                isLoggedIn.value = false;
                needUserInfo.value = false;
                resetUserInfo();
                reject(err);
              });
          } else {
            resolve(false);
          }
        }
      });
    });
  };

  // 跳转到登录页
  const goToLogin = (fromPath?: string) => {
    let url = ROUTES.LOGIN;
    if (fromPath) {
      url += `?from=${encodeURIComponent(fromPath)}`;
    }
    uni.navigateTo({
      url: url
    });
  };
  
  // 跳转到用户信息完善页
  const goToUserInfoPage = () => {
    uni.navigateTo({
      url: '/pages/userInfo/userInfo'
    });
  };

  // 页面显示时检查登录状态
  onShow(() => {
    checkLoginStatus();
  });

  return {
    isLoggedIn,
    needUserInfo,
    userInfo,
    checkLoginStatus,
    handleWxLogin,
    chooseAvatar,
    uploadAvatar,
    updateUserInfo,
    handleLogout,
    goToLogin,
    goToUserInfoPage
  };
} 